#include "mainwindow.hpp"
#include "ui_mainwindow.h"
#include "InfoDispatcher.hpp"

#include <QDebug>
#include <QObject>

MainWindow::MainWindow(QWidget *parent) :
   QMainWindow(parent),
   ui(new Ui::MainWindow),
   m_running(false)

{
   ui->setupUi(this);

   setupUI();
   setupConnections();

}

MainWindow::~MainWindow()
{
   delete ui;
}

void MainWindow::setupConnections()
{
   connect(ui->submitButton, SIGNAL(clicked()),this,SLOT(startOrStopClicked()));
   connect(&m_infoDispatcher, SIGNAL(finished(bool)),this,SLOT(dispatcherFinished(bool)));
   connect(&timer,SIGNAL(timeout()),&m_infoDispatcher,SLOT(run()));
}

void MainWindow::startOrStopClicked()
{
   if(!m_running)
   {
      if(isAtLeastOneValueSet())
      {
         runDispatcher();
         timer.setInterval(ui->intervalSpinBox->value()*1000);
         timer.start();

         ui->statusBar->clearMessage();
         ui->submitButton->setText("Stop");
         m_running = !m_running;
      }
      else
      {
         ui->statusBar->showMessage(tr("Please fill in the form."),5000);
      }
   }
   else
   {

      timer.stop();

      ui->submitButton->setText("Start");
      m_running = !m_running;
   }


}

void MainWindow::dispatcherFinished(bool ok)
{
   if(ok)
   {
      ui->statusBar->showMessage(tr("Flats evaluated successfully."), 5000);
   }
   else{
      ui->statusBar->showMessage(tr("Ouch, a failure!"), 5000);
   }
}

void MainWindow::keyPressEvent(QKeyEvent * event)
{
   if(event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return)
   {
      startOrStopClicked();
   }
}

void MainWindow::setupUI()
{
   setWindowTitle(tr("Better Living"));


   int interval = 10;
   ui->intervalSpinBox->setValue(interval);
   ui->intervalSpinBox->setMinimum(interval);
   ui->intervalSpinBox->setSingleStep(interval);
}

void MainWindow::runDispatcher()
{
   QString town = ui->townEdit->text();
   QString type = ui->typeCombo->currentText();
   float maxRent = ui->rentEdit->text().toFloat();
   float minRooms = ui->roomsEdit->text().toFloat();

   m_infoDispatcher.setKeywords(town,maxRent,minRooms,type);
   m_infoDispatcher.run();
}

bool MainWindow::isAtLeastOneValueSet() const
{
   QString town = ui->townEdit->text();
   QString type = ui->typeCombo->currentText();
   float maxRent = ui->rentEdit->text().toFloat();
   float minRooms = ui->roomsEdit->text().toFloat();

   return ((!QString(town /*+ type*/).isEmpty()) || (minRooms + maxRent > 0));
}
